﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RestSharp;

namespace Openapi.Weibo
{
    /// <summary>
    /// The OAuth 2 authenticator using the authorization request header field.
    /// </summary>
    /// <remarks>
    /// Based on http://tools.ietf.org/html/draft-ietf-oauth-v2-10#section-5.1.1
    /// </remarks>
    public class HeaderAuthenticator : OAuth2Authenticator
    {
        /// <summary>
        /// Stores the Authoriztion header value as "OAuth accessToken". used for performance.
        /// </summary>
        private readonly string _authorizationValue;

        /// <summary>
        /// Initializes a new instance of the <see cref="OAuth2AuthorizationRequestHeaderAuthenticator"/> class.
        /// </summary>
        /// <param name="accessToken">
        /// The access token.
        /// </param>
        public HeaderAuthenticator(string accessToken)
            : base(accessToken)
        {
            // Conatenate during constructor so that it is only done once. can improve performance.
            _authorizationValue = "OAuth2 " + accessToken;
        }

        public override void Authenticate(IRestClient client, IRestRequest request)
        {
            // only add the Authorization parameter if it hasn't been added.
            if (!request.Parameters.Any(p => p.Name.Equals("Authorization", StringComparison.OrdinalIgnoreCase)))
            {
                request.AddParameter("Authorization", _authorizationValue, ParameterType.HttpHeader);
            }
        }
    }


    /// <summary>
    /// The OAuth 2 authenticator using URI query parameter.
    /// </summary>
    /// <remarks>
    /// Based on http://tools.ietf.org/html/draft-ietf-oauth-v2-10#section-5.1.2
    /// </remarks>
    public class QueryParamAuthenticator : OAuth2Authenticator
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="QueryParamAuthenticator"/> class.
        /// </summary>
        /// <param name="accessToken">
        /// The access token.
        /// </param>
        public QueryParamAuthenticator(string accessToken)
            : base(accessToken)
        {
        }

        public override void Authenticate(IRestClient client, IRestRequest request)
        {
            request.AddParameter("oauth_token", AccessToken, ParameterType.GetOrPost);
        }
    }
}
